<template>
  <div id="Material">
    <Filters
      block
      :form="searchForm"
      :filterData="filterData"
      @confirm="changePage(1)"
    />
    <div class="container">
      <div class="tree-box">
        <div class="left-tree">
          <a-input-search style="margin-bottom: 8px" v-model="searchValue" placeholder="请输入分类名称" @change="onChange" />
          <a-tree
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            :selectedKeys="selectedKeys"
            :replaceFields="replaceFields"
            @expand="onExpand"
            @select="selectTree"
          >
            <template slot='title' slot-scope={name}>
              <span v-html="name.replace(new RegExp(searchValue,'g'),'<span style=color:#f50>' + searchValue + '</span>')"></span>
            </template>
          </a-tree>
        </div>
        <div class="right-table">
          <DataTable
            rowKey="id"
            :btns="btns"
            :showConfig="false"
            :tableData="Data"
            :tableColumn="tableColumn"
            :pageConfig="pageConfig"
            @refresh="getList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import util from '@/util/util';
import rules from '@/util/rules';
import md5 from 'js-md5';
import { WULIAO_EXPORT, WULIAO_IMPORT } from '@/api/global';

@Component
export default class Material extends Vue {
  searchForm: any = {
    searchValue: ''
  };
  get filterData () {
    return {
      searchValue: {
        label: '物料编码/名称',
        type: 'input',
        template: {
          placeholder: '请输入物料编码/名称',
          clearable: true
        }
      }
    };
  }
  selectedRowKeys: any[] = []
  Data: any[] = [{}];
  tableColumn: any = {
    ncMaterielCode: {
      label: '物资编码',
      minWidth: 120
    },
    ncMaterielName: {
      label: '物资名称',
      minWidth: 120
    }
    // userName: {
    //   label: '规格',
    //   minWidth: 120
    // },
    // roleName: {
    //   label: '型号',
    //   minWidth: 100
    // },
    // roleName2: {
    //   label: '单位',
    //   minWidth: 100
    // },
    // roleName3: {
    //   label: '采购价',
    //   minWidth: 100
    // }
  };
  pageConfig: any = {
    current: 1,
    total: 10,
    pageSize: 10,
    onChange: this.changePage
  };
  expandedKeys: any[] = []
  searchValue: string = ''
  autoExpandParent: boolean = true
  treeData: any[] = []
  selectedKeys: any[] = []
  checkedKeys: any[] = []
  backupsExpandedKeys: any[] = []
  replaceFields: any = {
    children: 'child',
    title: 'name',
    key: 'id'
  }
  btns: any[] = [
    // {
    //   label: '导入',
    //   upload: true,
    //   action: util.getApiUrl() + WULIAO_IMPORT,
    //   accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel',
    //   icon: 'download',
    //   callback: (res: any) => this.uploadSuccess(res)
    // },
    // {
    //   label: '同步'
    // },
    {
      label: '导出',
      icon: 'export',
      callback: this.exportList
    }
  ]
  departId: any = ''
  treeValue: any = ''
  searchStr: any = ''



  init () {
    this.getList()
    this.getTreeData()
  }

  // 获取树形结构
  getTreeData () {
    let data = { code: this.treeValue }
    this.$api.goodsNcMaterielTypeListFetch(data).then((res: any) => {
      this.treeData = res.data.map((item:any) => ({
        id: item.id,
        name: item.name,
        code: item.code,
        scopedSlots: {title: 'title'},
        child: item.child && item.child.map((item2:any) => ({
          id: item2.id,
          name: item2.name,
          code: item2.code,
          scopedSlots: {title: 'title'},
          child: item2.child && item2.child.map((item3:any) => ({
            id: item3.id,
            name: item3.name,
            code: item3.code,
            scopedSlots: {title: 'title'},
            child: item3.child && item3.child.map((item4:any) => ({
              id: item4.id,
              name: item4.name,
              code: item4.code,
              scopedSlots: {title: 'title'}
            }))
          }))
        }))
      })
      )
    })
  }
  get getSearchForm () {
    let searchForm = JSON.parse(JSON.stringify(this.searchForm));
    let { current, pageSize } = this.pageConfig
    let form = Object.assign(searchForm, {
      page: current,
      size: pageSize,
      id: this.departId
    });
    return form;
  }
  getList () {
    let data = this.getSearchForm
    this.$api.wuLiaoWuLiaoListFetch(data).then((res: any) => {
      this.Data = res.data.records
      this.pageConfig.total = res.data.total
      if (!this.Data.length && this.pageConfig.current > 1) {
        --this.pageConfig.current
        this.getList()
      }
    })
  }
  onExpand (expandedKeys: any[]) {
    this.expandedKeys = expandedKeys;
    this.autoExpandParent = false;
  }
  // 选择树
  selectTree (selectedKeys: any) {
    console.log('选择树', selectedKeys)
    this.departId = selectedKeys[0]
    this.getList()
  }
  onChange (e: any) {
    const value = e.target.value;
    if (value === '') {
          this.expandedKeys = [];
        } else {
          // 首先将展开项与展开项副本置为空
          this.expandedKeys = [];
          this.backupsExpandedKeys = [];
          // 获取所有存在searchValue的节点
          let candidateKeysList = this.getkeyList(value, this.treeData, []);

          // 遍历满足条件的所有节点
          candidateKeysList.map(
            (item:any) => {
              // 获取每个节点的母亲节点
              var key = this.getParentKey(item, this.treeData);
              if (key && !this.backupsExpandedKeys.some(item => item === key)) { this.backupsExpandedKeys.push(key); }
            }
          )
          let length = this.backupsExpandedKeys.length;
          for (let i = 0; i < length; i++) {
            this.getAllParentKey(this.backupsExpandedKeys[i], this.treeData)
          }
          this.expandedKeys = this.backupsExpandedKeys.slice();
        }
  }
  // 获取节点中含有value的所有key集合
  getkeyList (value:any, tree:any, keyList:any) {
    // 遍历所有同一级的树
    for (let i = 0; i < tree.length; i++) {
      let node = tree[i];
      if (node.name.indexOf(value) > -1) {
        keyList.push(node.id);
      }
      if (node.child) {
          this.getkeyList(value, node.child, keyList);
      }
    }
    return keyList;
  }
  // 该递归主要用于获取key的父亲节点的key值
  getParentKey (key:any, tree:any) {
    let parentKey :any
    let temp :any;
    // 遍历同级节点
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.child) {
        if (node.child.some((item:any) => item.id === key)) {
          parentKey = node.id;
        } else if (temp = this.getParentKey(key, node.child)) {
          // parentKey = this.getParentKey(key,node.children)
          // 改进，避免二次遍历
          parentKey = temp;
        }
      }
    }
    return parentKey;
  }
  // 获取该节点的所有祖先节点
  getAllParentKey (key:any, tree:any) {
    var parentKey = '';
    if (key) {
      // 获得父亲节点
      parentKey = this.getParentKey(key, tree);
      if (parentKey) {
      	// 如果父亲节点存在，判断是否已经存在于展开列表里，不存在就进行push
        if (!this.backupsExpandedKeys.some(item => item === parentKey)) {
          this.backupsExpandedKeys.push(parentKey);
        }
        // 继续向上查找祖先节点
        this.getAllParentKey(parentKey, tree)
      }
    }
  }
  changePage (val: number) {
    this.pageConfig.current = val;
    this.getList();
  }
  searchHandle () {
    this.pageConfig.current = 1;
    this.getList();
  }
  delHandle ({ adminId }: any) {
    let data = { adminId };
    this.$api.adminDeleteFetch(data).then((res: any) => {
      this.$message.success('删除成功');
      this.getList();
    });
  }
  // 导出
  exportList () {
    let form = this.getSearchForm();
    util.exportExcelFun(form, WULIAO_EXPORT);
  }
  // 导入
  uploadSuccess (res: any) {
      if (res.code === 0) {
          this.getList() // 重新请求核对信息列表数据
      } else {
          this.$message.error(res.msg)
      }
  }
}
</script>

<style lang="scss" scoped>
#Material{
  .tree-box{
    width: 100%;
    display: flex;
    .left-tree{
      width: 20%;
      margin-right: 40px;
      flex-shrink: 0;

    }
    .right-table{
      flex: 1;
    }
  }
}
</style>
